﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace GlxRRSDB.Utils
{
    public static class DateTimeExtensions
    {
        public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
        {
            int diff = dt.DayOfWeek - startOfWeek;
            if (diff < 0)
            {
                diff += 7;
            }

            return dt.AddDays(-1 * diff).Date;
        }
        public static DateTime EndOfWeek(this DateTime dt, DayOfWeek startOfWeek)
        {
            int diff = dt.DayOfWeek - startOfWeek;
            if (diff < 0)
            {
                diff += 7;
            }

            return dt.AddDays(-1 * diff + 6).Date;
        }
        public static DateTime StartOfMonth(this DateTime dateTime)
        {
            return new DateTime(dateTime.Year, dateTime.Month, 1);
        }
        public static DateTime EndOfMonth(this DateTime dateTime)
        {
            DateTime firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1);
            return firstDayOfTheMonth.AddMonths(1).AddDays(-1);
        }
        public static DateTime StartOfQuarter(this DateTime datetime)
        {
            int quarterNumber = (datetime.Month - 1) / 3 + 1;
            return new DateTime(datetime.Year, (quarterNumber - 1) * 3 + 1, 1);
        }
        public static DateTime EndOfQuarter(this DateTime datetime)
        {
            int quarterNumber = (datetime.Month - 1) / 3 + 1;
            DateTime firstDayOfQuarter = new DateTime(datetime.Year, (quarterNumber - 1) * 3 + 1, 1);
            return firstDayOfQuarter.AddMonths(3).AddDays(-1);
        }
        public static DateTime StartOfYear(this DateTime datetime)
        {
            return new DateTime(datetime.Year, 1, 1);
        }
        public static DateTime EndOfYear(this DateTime datetime)
        {
            return new DateTime(datetime.Year, 12, 31);
        }
        public static int CurrentWeekNumber(this DateTime datetime)
        {
            CultureInfo ciCurr = CultureInfo.CurrentCulture;
            int weekNum = ciCurr.Calendar.GetWeekOfYear(datetime, ciCurr.DateTimeFormat.CalendarWeekRule, DayOfWeek.Friday);
            return weekNum; 

        }
    }
}
